﻿<%@ Page AutoEventWireup="true" CodeBehind="Register.aspx.cs" Inherits="AssetManage.Account.Register" Language="C#" MasterPageFile="~/Site.Master" Title="注册" %>

<%@ MasterType VirtualPath="~/Site.Master" %>

<asp:Content runat="server" ID="BodyContent" ContentPlaceHolderID="MainContent">
<h2><%: Title %></h2>
<script type="text/javascript" src="/Scripts/CryptoJS/sha256.js"></script>
<script type="text/javascript" src="/Scripts/CryptoJS/enc-base64-min.js"></script>
<script type="text/javascript">
    var UserName = "#<%= UserName.ClientID %>";

    var UserID = "#<%= UserID.ClientID %>";
    var UserID_Error = "#<%= UserID_Error.ClientID %>";

    var Password = "#<%= Password.ClientID %>";
    var Password_Error = "#<%= Password_Error.ClientID %>";

    var ConfirmPassword = "#<%= ConfirmPassword.ClientID %>";
    var ConfirmPassword_Error = "#<%= ConfirmPassword_Error.ClientID %>";

    var Email = "#<%= Email.ClientID %>";
    var Email_Error = "#<%= Email_Error.ClientID %>";

    var EmailCaptcha = "#<%= EmailCaptcha.ClientID %>";
    var EmailCaptcha_Error = "#<%= EmailCaptcha_Error.ClientID %>";

    var Captcha = "#<%= Captcha.ClientID %>";
    var Captcha_Error = "#<%= Captcha_Error.ClientID %>";

    var CreateUser = "#CreateUser";

    $(function() {
        $("#SendEmail").attr("disabled", "disabled");
        $(EmailCaptcha).attr("readOnly", true);
        $(CreateUser).attr("disabled", "disabled");

        $(UserID).change(function() {
            $(CreateUser).attr("disabled", "disabled");

            if ($(UserID).val() === "") {
                $(UserID_Error).text("请输入用户名。");
            } else {
                var reg = /^[a-zA-Z]\w{6,15}$/;
                if (!reg.test($(UserID).val())) {
                    $(UserID_Error).text("请输入正确的用户名。");
                } else {
                    var sendData = {
                        "action": "exist",
                        "userid": $(UserID).val()
                    };
                    $.ajax({
                        type: "POST",
                        url: "/Handler/Validate",
                        data: sendData,
                        beforeSubmit: function() {
                            $(UserID_Error).attr("value", "正在验证身份……");
                        },
                        success: function(response) {
                            var responseData = eval("(" + response + ")");
                            if (responseData.exist) {
                                $(UserID_Error).text("该用户名已存在。请输入其他的用户名。");
                            } else {
                                $(UserID_Error).text("");
                                if (HaveNoError()) {
                                    $(CreateUser).removeAttr("disabled");
                                }
                            }
                            if (responseData.error === "Cookie_Error") {
                                window.location.replace("/Error/Cookie");
                                return;
                            }
                        }
                    });
                }
            }
        });

        $(Password).change(function() {
            $(CreateUser).attr("disabled", "disabled");
            if ($(Password).val() === "") {
                $(Password_Error).text("请输入密码。");
            } else {
                var reg = /^([a-zA-Z0-9-`=\\\[\];',./~!@#$%\^&*()_+|{}:"<>?]){6,16}$/;
                if (!reg.test($(Password).val())) {
                    $(Password_Error).text("请输入正确的密码。");
                } else {
                    $(Password_Error).text("");
                    if (HaveNoError()) {
                        $(CreateUser).removeAttr("disabled");
                    }
                }
            }
        });

        $(ConfirmPassword).change(function() {
            $(CreateUser).attr("disabled", "disabled");
            if ($(ConfirmPassword).val() === "") {
                $(ConfirmPassword_Error).text("请再次输入密码。");
            } else {
                if ($(Password).val() !== $(ConfirmPassword).val()) {
                    $(ConfirmPassword_Error).text("两次输入的密码不匹配。");
                } else {
                    $(ConfirmPassword_Error).text("");
                    if (HaveNoError()) {
                        $(CreateUser).removeAttr("disabled");
                    }
                }
            }
        });

        $(Email).change(function() {
            if (LeftSeconds < 60) {
                $("#SendEmail").attr("disabled", "disabled");
                $(EmailCaptcha).attr("readOnly", true);
                $(EmailCaptcha).val("");
                return;
            }

            $(CreateUser).attr("disabled", "disabled");
            if ($(Email).val() === "") {
                $(Email_Error).text("请输入电子邮箱。");
            } else {
                var reg = /^(\w)+(\.\w+)*@(\w)+((\.\w{2,3}){1,3})$/;
                if (!reg.test($(Email).val())) {
                    $(Email_Error).text("请输入正确的电子邮箱。");
                } else {
                    if (!$("#SendEmail").attr("readOnly")) {
                        if ($(Email).attr("disabled") !== "disabled") {
                            var sendData = {
                                section: "email",
                                email: $(Email).val()
                            };
                            $.ajax({
                                type: "POST",
                                url: "/Handler/Validate",
                                data: sendData,
                                beforeSubmit: function() {
                                    $("#SendEmail").val("正在验证……");
                                    $("#SendEmail").attr("disabled", "disabled");
                                    $(EmailCaptcha).attr("readOnly", true);
                                    $(EmailCaptcha).val("");
                                },
                                success: function(response) {
                                    var responseData = eval("(" + response + ")");
                                    if (responseData.error === "Cookie_Error") {
                                        window.location.replace("/Error/Cookie");
                                        return;
                                    }
                                    if (responseData.exist) {
                                        $(Email_Error).text("该电子邮箱已存在。请输入其他的电子邮箱。");
                                    } else {
                                        $("#SendEmail").removeAttr("disabled");
                                        $(Email_Error).text("");
                                        if (HaveNoError()) {
                                            $(CreateUser).removeAttr("disabled");
                                        }
                                    }
                                }
                            });
                        }
                    }
                }
            }
        });

        $(EmailCaptcha).change(function() {
            $(CreateUser).attr("disabled", "disabled");
            if ($(EmailCaptcha).attr("readOnly")) {
            } else {
                if ($(EmailCaptcha).val() === "") {
                    $(EmailCaptcha_Error).text("请填入邮件验证码");
                }
                var reg = /^\w{16}$/;
                if (!reg.test($(EmailCaptcha).val())) {
                    $(EmailCaptcha_Error).text("请填入正确的邮件验证码");
                } else {
                    var sendData = {
                        section: "emailcaptcha",
                        emaicaptcha: $(EmailCaptcha).val()
                    };
                    $.ajax({
                        type: "POST",
                        url: "/Handler/Validate",
                        data: sendData,
                        beforeSubmit: function() {
                            $(EmailCaptcha_Error).val("正在验证……");
                        },
                        success: function(response) {
                            var responseData = eval("(" + response + ")");
                            if (responseData.success) {
                                $(EmailCaptcha_Error).text("");
                                if (HaveNoError()) {
                                    $(CreateUser).removeAttr("disabled");
                                }
                            } else {
                                $(EmailCaptcha_Error).text("请填入正确的邮件验证码");
                                if (responseData.error === "Cookie_Error") {
                                    window.location.replace("/Error/Cookie");
                                    return;
                                }
                            }
                        }
                    });
                }
            }
        });

        $(Captcha).change(function() {
            $(CreateUser).attr("disabled", "disabled");
            if ($(Captcha).val() === "") {
                $(Captcha_Error).text("请输入验证码。");
            } else {
                var reg = /^[^jiloxJILOX10]{5}$/;
                if (!reg.test($(Captcha).val())) {
                    $(Captcha_Error).text("请输入正确的验证码。");
                } else {
                    var sendData = {
                        section: "captcha",
                        captcha: $(Captcha).val()
                    };
                    $.ajax({
                        type: "POST",
                        url: "/Handler/Validate",
                        data: sendData,
                        beforeSubmit: function() {
                            $(Captcha_Error).val("正在验证……");
                        },
                        success: function(response) {
                            var responseData = eval("(" + response + ")");
                            if (responseData.success) {
                                $(Captcha_Error).text("");
                                if (HaveNoError()) {
                                    $(CreateUser).removeAttr("disabled");
                                }
                            } else {
                                $(Captcha_Error).text("请输入正确的验证码。");
                                if (responseData.error === "Cookie_Error") {
                                    window.location.replace("/Error/Cookie");
                                    return;
                                }
                            }
                        }
                    });
                }
            }
        });

        $("#SendEmail").click(function() {
            $("#SendEmail").attr("disabled", "disabled");
            $("#SendEmail").attr("value", "正在等待服务器响应……");
            var sendData = {
                action: "send",
                username: $(UserName).find("option:selected").text(),
                email: $(Email).val()
            };
            $.ajax({
                type: "POST",
                url: "/Handler/Email",
                data: sendData,
                success: function(response) {
                    $("#SendEmail").attr("disabled", "disabled");
                    var responseData = eval("(" + response + ")");
                    if (responseData.success) {
                        $(ShowSendEmailResultDialog("success", "请将序列号为[" + responseData.id + "]的邮件验证码填入。"));
                        $(EmailCaptcha).attr("readOnly", false);
                    }
                    switch (responseData.error) {
                    case "Email_IsExist":
                        $(Email_Error).text("该电子邮箱已存在。请输入其他的电子邮箱。");
                        $("#SendEmail").attr("value", "发送验证邮件");
                        break;
                    case "Send_Error":
                        $(CreateUser).attr("disabled", "disabled");
                        $(ShowSendEmailResultDialog("error", ""));
                        break;
                    case "Cookie_Error":
                        window.location.replace("/Error/Cookie");
                        return;
                    }
                }
            });
        });

        $("#CaptchaImg").click(function() {
            $("#CaptchaImg").attr("src", "/Handler/Captcha?action=get&random=" + Math.random());
            $(Captcha).val("");
            $(Captcha_Error).text("请输入验证码。");
            $(CreateUser).attr("disabled", "disabled");
        });

        $(CreateUser).click(function() {
            if (!HaveNoError()) {
                $(CreateUser).attr("value", "注册");
                $(CreateUser).attr("disabled", "disabled");
                return;
            }

            $(CreateUser).attr("value", "正在提交……");
            $(CreateUser).attr("disabled", "disabled");
            $("#message").text("");

            var sendData = {
                action: "regist",
                tableid: $(UserName).find("option:selected").val(),
                userid: $(UserID).val(),
                password: CryptoJS.SHA256($(Password).val()).toString(CryptoJS.enc.Hex).toUpperCase(),
                email: $(Email).val(),
                emailcaptcha: $(EmailCaptcha).val(),
                captcha: $(Captcha).val()
            };
            $.ajax({
                type: "POST",
                url: "/Handler/Account",
                data: sendData,
                success: function(response) {
                    var responseData = eval("(" + response + ")");
                    if (responseData.success) {
                        ShowResultDialog("success");
                    } else {
                        $(CreateUser).attr("value", "注册");
                        $(CreateUser).attr("disabled", "disabled");
                        switch (responseData.error) {
                        case "Captcha_Error":
                            $(Captcha_Error).text("请输入正确的验证码。");
                            break;
                        case "EmailCaptcha_Error":
                            $(EmailCaptcha_Error).text("请填入正确的邮件验证码");
                            break;
                        case "Email_IsExist":
                            $("#SendEmail").attr("disabled", "disabled");
                            $(EmailCaptcha).attr("readOnly", true);
                            $(EmailCaptcha).val("");
                            $(Email_Error).text("该电子邮箱已存在。请输入其他的电子邮箱。");
                            break;
                        case "UserID_IsExist":
                            $(UserID_Error).text("该用户名已存在。请输入其他的用户名。");
                            break;
                        case "Email_Error":
                            $("#SendEmail").attr("disabled", "disabled");
                            $(EmailCaptcha).attr("readOnly", true);
                            $(EmailCaptcha).val("");
                            $(Email_Error).text("请输入正确的电子邮箱。");
                            break;
                        case "Password_Error":
                            $(Password_Error).text("请输入正确的密码。");
                            break;
                        case "Cookie_Error":
                            window.location.replace("/Error/Cookie");
                            return;
                        }
                    }
                }
            });
        });
    });

    function HaveNoError() {
        var result = true;
        $(".form-horizontal :text").each(function() {
            if ($(this).val() === "") {
                result = false;
            }
        });
        $(".form-horizontal :password").each(function() {
            if ($(this).val() === "") {
                result = false;
            }
        });
        $("[id$='_Error']").each(function() {
            if ($(this).text() !== "") {
                result = false;
            }
        });
        return result;
    }

    var LeftSeconds = 90;

    function DisableSendEmail() {
        if (LeftSeconds > 0) {
            $("#SendEmail").attr("disabled", "disabled");
            $("#SendEmail").attr("value", "请于" + LeftSeconds + "秒后再试……");
            setTimeout(DisableSendEmail, 1000);
            LeftSeconds--;
        } else {
            $("#SendEmail").removeAttr("disabled");
            $("#SendEmail").attr("value", "发送验证邮件");
            LeftSeconds = 90;
            $(Email).change();
        }
    }

    function RefreshProgress() {
        var value = $("#progress").progressbar("value");
        value += 5;
        $("#progress").progressbar("value", value);
        if (value < 100) {
            setTimeout(RefreshProgress, (Math.random() * 1000) / 10);
        }
    }

    function ShowSendEmailResultDialog(code, message) {
        $(function() {
            $("#progress").progressbar({
                value: 0,
                change: function() {
                    var value = $("#progress").progressbar("value");
                    if (value >= 100) {
                        $(".ui-dialog-buttonpane button").show();
                        if (code === "success") {
                            $("#message").text(message);
                            $("#dialog").dialog("option", "title", "发送成功!");
                            $(DisableSendEmail);
                        } else {
                            $("#dialog").dialog("option", "title", "发送失败!");
                            $("#error").text("发送失败!");
                        }
                        return;
                    }
                    $(".ui-dialog-buttonpane button").hide();
                    $("#message").text("正在发送验证邮件……");
                }
            });
            $("#dialog").dialog({
                title: "请稍候……",
                closeText: "关闭",
                modal: true,
                resizable: false,
                buttons: {
                    "确定": function() {
                        $(this).dialog("close");
                    }
                },
                beforeClose: function() {
                    var value = $("#progress").progressbar("value");
                    if (value < 100) {
                        return false;
                    }
                    return true;
                }
            });
            $(RefreshProgress);
        });
    };

    function ShowResultDialog(code) {
        $(function() {
            $("#dialog").dialog({
                title: "服务器消息",
                closeText: "关闭",
                modal: true,
                resizable: false,
                buttons: {
                    "确定": function() {
                        if (code === "success") {
                            $(this).dialog("close");
                            window.location.href = "/Handler/Account/Login";
                        }
                    }
                },
                beforeClose: function() {
                    if (code === "success") {
                        return false;
                    }
                    return true;
                }
            });
            if (code === "success") {
                $("#success").text("注册成功!");
            } else {
                $("#error").text("注册失败!");
            }
        });
    };
</script>
<div class="form-horizontal">
    <h4>创建新帐户。</h4>
    <hr/>
    <div class="form-group">
        <asp:Label runat="server" AssociatedControlID="UserName" CssClass="col-md-2 control-label">账户</asp:Label>
        <div class="col-md-10">
            <asp:DropDownList ID="UserName" CssClass="form-control" runat="server" Font-Size="Medium" DataSourceID="Account_SqlDataSource" DataTextField="RealName" DataValueField="TableID">
            </asp:DropDownList>
            <asp:SqlDataSource ID="Account_SqlDataSource" runat="server" ConnectionString="<%$ ConnectionStrings:Account_ConnectionString %>" ProviderName="<%$ ConnectionStrings:Account_ConnectionString.ProviderName %>" SelectCommand="SELECT [TableID], [RealName] FROM [Account] WHERE ([Used] = 0) ORDER BY [TableID]"></asp:SqlDataSource>
        </div>
    </div>
    <div class="form-group">
        <asp:Label runat="server" AssociatedControlID="UserID" CssClass="col-md-2 control-label">用户名</asp:Label>
        <div class="col-md-10">
            <asp:TextBox data-toggle="tooltip" data-placement="bottom" title="用户名只能以字母开头，不能含有特殊符号及中文字符，长度至少6位，至多16位。" runat="server" ID="UserID" CssClass="form-control" MaxLength="16" AutoCompleteType="DisplayName"/>
            <asp:Label ID="UserID_Error" runat="server" CssClass="text-danger"></asp:Label>
        </div>
    </div>
    <div class="form-group">
        <asp:Label runat="server" AssociatedControlID="Password" CssClass="col-md-2 control-label">密码</asp:Label>
        <div class="col-md-10">
            <asp:TextBox runat="server" data-toggle="tooltip" data-placement="bottom" title="密码长度至少6位，至多16位。" ID="Password" TextMode="Password" CssClass="form-control" AutoCompleteType="Disabled" MaxLength="16"/>
            <asp:Label ID="Password_Error" runat="server" CssClass="text-danger"></asp:Label>
        </div>
    </div>
    <div class="form-group">
        <asp:Label runat="server" AssociatedControlID="ConfirmPassword" CssClass="col-md-2 control-label">确认密码</asp:Label>
        <div class="col-md-10">
            <asp:TextBox runat="server" data-toggle="tooltip" data-placement="bottom" title="密码长度至少6位，至多16位。" ID="ConfirmPassword" TextMode="Password" CssClass="form-control" AutoCompleteType="Disabled" MaxLength="16"/>
            <asp:Label ID="ConfirmPassword_Error" runat="server" CssClass="text-danger"></asp:Label>
        </div>
    </div>
    <div class="form-group">
        <asp:Label runat="server" AssociatedControlID="Email" CssClass="col-md-2 control-label">电子邮箱</asp:Label>
        <div class="col-md-10">
            <asp:TextBox runat="server" ID="Email" CssClass="form-control" TextMode="Email" MaxLength="32" AutoCompleteType="Email"/>
            <asp:Label ID="Email_Error" runat="server" CssClass="text-danger"></asp:Label>
        </div>
        <asp:Label runat="server" CssClass="col-md-2 control-label"></asp:Label>
        <div class="col-md-10">
            <input id="SendEmail" type="button" value="发送验证邮件" class="btn btn-primary btn-lg" style="margin-top: 14px"/>
        </div>
    </div>
    <div class="form-group">
        <asp:Label runat="server" AssociatedControlID="EmailCaptcha" CssClass="col-md-2 control-label">邮件验证码</asp:Label>
        <div class="col-md-10">
            <asp:TextBox data-toggle="tooltip" data-placement="bottom" title="邮件验证码区分大小写。" runat="server" ID="EmailCaptcha" MaxLength="16" CssClass="form-control"/>
            <asp:Label ID="EmailCaptcha_Error" runat="server" CssClass="text-danger"></asp:Label>
        </div>
    </div>
    <div class="form-group">
        <asp:Label runat="server" AssociatedControlID="Captcha" CssClass="col-md-2 control-label">验证码</asp:Label>
        <div class="col-md-10">
            <img id="CaptchaImg" alt="点击更换图片" data-toggle="tooltip" data-placement="bottom" title="点击更换图片" src="/Handler/Captcha" class="form-control" style="border: none; cursor: pointer; height: 60px; width: 280px;"/>
            <asp:TextBox data-toggle="tooltip" data-placement="bottom" title="验证码不区分大小写" runat="server" ID="Captcha" MaxLength="5" CssClass="form-control"/>
            <asp:Label ID="Captcha_Error" runat="server" CssClass="text-danger"></asp:Label>
        </div>
    </div>
    <div class="form-group">
        <div class="col-md-offset-2 col-md-10">
            <input id="CreateUser" type="button" value="注册" class="btn btn-primary btn-lg"/>
        </div>
    </div>
</div>
<div id="dialog">
    <div id="progress"></div>
    <div id="message" style="font-size: medium"></div>
    <div id="success" class="text-success" style="font-size: medium"></div>
    <div id="error" class="text-danger" style="font-size: medium"></div>
</div>
</asp:Content>